/**
 * 研发项目分支管理业务逻辑
 */
// 直接导入相关模块，避免使用path_resolver
const ProjectHelpers = require('../../config/project_helpers_config');
const dataHelper = ProjectHelpers.dataHelper;
const timeHelper = ProjectHelpers.timeHelper;
const pageHelper = ProjectHelpers.pageHelper;
const cloudHelper = ProjectHelpers.cloudHelper;
const cacheHelper = ProjectHelpers.cacheHelper || require('../../helpers/cache_helper');

// 添加ResearchBranchService模拟实现
let ResearchBranchService;
try {
    ResearchBranchService = require('../../services/research_branch_service.js');
    console.log('研发分支服务模块导入成功');
} catch (e) {
    console.warn('研发分支服务模块导入失败:', e);
    // 定义一个模拟的ResearchBranchService类
    ResearchBranchService = class ResearchBranchService {
        async isBranch(projectId) {
            console.log('模拟检查项目是否为分支:', projectId);
            return false;
        }
        
        async getParentProject(projectId) {
            console.log('模拟获取父项目:', projectId);
            return null;
        }
        
        async createBranch(parentId, name, desc) {
            console.log('模拟创建分支:', { parentId, name, desc });
            return { _id: 'mock_branch_id' };
        }
        
        async mergeBranch(sourceId, targetId) {
            console.log('模拟合并分支:', { sourceId, targetId });
            return true;
        }
        
        async updateBranch(branchId, name, desc) {
            console.log('模拟更新分支:', { branchId, name, desc });
            return true;
        }
        
        async deleteBranch(branchId) {
            console.log('模拟删除分支:', branchId);
            return true;
        }
        
        async getBranchVersions(branchId) {
            console.log('模拟获取分支版本:', branchId);
            return [];
        }
        
        async switchToVersion(branchId, versionId) {
            console.log('模拟切换版本:', { branchId, versionId });
            return true;
        }
    };
}

// 缓存
const CACHE_RESEARCH_BRANCH_LIST = 'CACHE_RESEARCH_BRANCH_LIST';
const CACHE_RESEARCH_IS_BRANCH = 'CACHE_RESEARCH_IS_BRANCH';
const CACHE_RESEARCH_PARENT = 'CACHE_RESEARCH_PARENT';
const CACHE_RESEARCH_VERSIONS = 'CACHE_RESEARCH_VERSIONS';
const CACHE_TIME = 30 * 60; // 缓存30分钟

/**
 * 研发项目分支业务逻辑
 */
class ResearchBranchBiz {

    /**
     * 获取项目分支列表
     * @param {String} projectId 项目ID
     * @returns {Promise} 查询结果
     */
    static async getBranchList(projectId) {
        if (!projectId) return { list: [], total: 0 };

        // 尝试从缓存获取
        const cacheKey = CACHE_RESEARCH_BRANCH_LIST + '_' + projectId;
        const cache = cacheHelper.get(cacheKey);
        if (cache) return cache;

        try {
            // 直接调用云函数获取分支列表
            const result = await cloudHelper.callCloudData('research/branch_list', { projectId });
            
            // 设置缓存
            cacheHelper.set(cacheKey, result, CACHE_TIME);
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.getBranchList 失败:', err);
            pageHelper.showModal('获取项目分支列表失败: ' + (err.message || '未知错误'));
            return { list: [], total: 0 };
        }
    }

    /**
     * 检查项目是否为分支
     * @param {String} projectId 项目ID
     * @returns {Promise<Boolean>} 是否为分支
     */
    static async isBranch(projectId) {
        if (!projectId) return false;

        // 尝试从缓存获取
        const cacheKey = CACHE_RESEARCH_IS_BRANCH + '_' + projectId;
        const cache = cacheHelper.get(cacheKey);
        if (cache !== null && cache !== undefined) return cache;

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.isBranch(projectId);

            // 设置缓存
            cacheHelper.set(cacheKey, result, CACHE_TIME);
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.isBranch 失败:', err);
            return false;
        }
    }

    /**
     * 获取父项目信息
     * @param {String} projectId 当前项目ID
     * @returns {Promise} 父项目信息
     */
    static async getParentProject(projectId) {
        if (!projectId) return null;

        // 尝试从缓存获取
        const cacheKey = CACHE_RESEARCH_PARENT + '_' + projectId;
        const cache = cacheHelper.get(cacheKey);
        if (cache) return cache;

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.getParentProject(projectId);

            // 设置缓存
            if (result) cacheHelper.set(cacheKey, result, CACHE_TIME);
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.getParentProject 失败:', err);
            pageHelper.showModal('获取父项目信息失败: ' + err.message);
            return null;
        }
    }

    /**
     * 创建项目分支
     * @param {String} parentId 父项目ID
     * @param {String} name 分支名称
     * @param {String} desc 分支描述
     * @returns {Promise} 创建结果
     */
    static async createBranch(parentId, name, desc = '') {
        if (!parentId) {
            pageHelper.showModal('父项目ID不能为空');
            return null;
        }
        if (!name) {
            pageHelper.showModal('分支名称不能为空');
            return null;
        }

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.createBranch(parentId, name, desc);

            // 清除相关缓存
            this.clearCache(parentId);
            
            pageHelper.showSuccessToast('创建分支成功');
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.createBranch 失败:', err);
            pageHelper.showModal('创建项目分支失败: ' + err.message);
            return null;
        }
    }

    /**
     * 合并项目分支
     * @param {String} sourceId 源分支ID
     * @param {String} targetId 目标项目ID
     * @returns {Promise} 合并结果
     */
    static async mergeBranch(sourceId, targetId) {
        if (!sourceId) {
            pageHelper.showModal('源分支ID不能为空');
            return false;
        }
        if (!targetId) {
            pageHelper.showModal('目标项目ID不能为空');
            return false;
        }

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.mergeBranch(sourceId, targetId);

            // 清除相关缓存
            this.clearCache(sourceId);
            this.clearCache(targetId);
            
            pageHelper.showSuccessToast('合并分支成功');
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.mergeBranch 失败:', err);
            pageHelper.showModal('合并项目分支失败: ' + err.message);
            return false;
        }
    }

    /**
     * 更新项目分支
     * @param {String} branchId 分支项目ID
     * @param {String} name 分支名称
     * @param {String} desc 分支描述
     * @returns {Promise} 更新结果
     */
    static async updateBranch(branchId, name, desc = '') {
        if (!branchId) {
            pageHelper.showModal('分支ID不能为空');
            return false;
        }
        if (!name) {
            pageHelper.showModal('分支名称不能为空');
            return false;
        }

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.updateBranch(branchId, name, desc);

            // 清除相关缓存
            this.clearCache(branchId);
            
            pageHelper.showSuccessToast('更新分支成功');
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.updateBranch 失败:', err);
            pageHelper.showModal('更新项目分支失败: ' + err.message);
            return false;
        }
    }

    /**
     * 删除项目分支
     * @param {String} branchId 分支项目ID
     * @returns {Promise} 删除结果
     */
    static async deleteBranch(branchId) {
        if (!branchId) {
            pageHelper.showModal('分支ID不能为空');
            return false;
        }

        try {
            const branchService = new ResearchBranchService();
            
            // 获取父项目，以便清除父项目缓存
            const parent = await this.getParentProject(branchId);
            
            const result = await branchService.deleteBranch(branchId);

            // 清除相关缓存
            this.clearCache(branchId);
            if (parent && parent._id) this.clearCache(parent._id);
            
            pageHelper.showSuccessToast('删除分支成功');
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.deleteBranch 失败:', err);
            pageHelper.showModal('删除项目分支失败: ' + err.message);
            return false;
        }
    }

    /**
     * 获取分支版本历史
     * @param {String} branchId 分支ID
     * @returns {Promise} 版本历史
     */
    static async getBranchVersions(branchId) {
        if (!branchId) return { list: [], total: 0 };

        // 尝试从缓存获取
        const cacheKey = CACHE_RESEARCH_VERSIONS + '_' + branchId;
        const cache = cacheHelper.get(cacheKey);
        if (cache) return cache;

        try {
            const branchService = new ResearchBranchService();
            const list = await branchService.getBranchVersions(branchId);
            const result = { list: list || [], total: list ? list.length : 0 };

            // 设置缓存
            cacheHelper.set(cacheKey, result, CACHE_TIME);
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.getBranchVersions 失败:', err);
            pageHelper.showModal('获取分支版本历史失败: ' + err.message);
            return { list: [], total: 0 };
        }
    }

    /**
     * 切换到指定版本
     * @param {String} branchId 分支ID
     * @param {String} versionId 版本ID
     * @returns {Promise} 切换结果
     */
    static async switchToVersion(branchId, versionId) {
        if (!branchId) {
            pageHelper.showModal('分支ID不能为空');
            return false;
        }
        if (!versionId) {
            pageHelper.showModal('版本ID不能为空');
            return false;
        }

        try {
            const branchService = new ResearchBranchService();
            const result = await branchService.switchToVersion(branchId, versionId);

            // 清除相关缓存
            this.clearCache(branchId);
            
            pageHelper.showSuccessToast('切换版本成功');
            return result;
        } catch (err) {
            console.error('ResearchBranchBiz.switchToVersion 失败:', err);
            pageHelper.showModal('切换到指定版本失败: ' + err.message);
            return false;
        }
    }

    /**
     * 清除相关缓存
     * @param {String} projectId 项目ID
     */
    static clearCache(projectId) {
        if (!projectId) return;

        // 清除该项目的所有相关缓存
        cacheHelper.remove(CACHE_RESEARCH_BRANCH_LIST + '_' + projectId);
        cacheHelper.remove(CACHE_RESEARCH_IS_BRANCH + '_' + projectId);
        cacheHelper.remove(CACHE_RESEARCH_PARENT + '_' + projectId);
        cacheHelper.remove(CACHE_RESEARCH_VERSIONS + '_' + projectId);
    }
}

module.exports = ResearchBranchBiz; 